package cn.xinfei.xdecision.data.core.frame.executors.collect.filter;


import com.google.common.collect.Lists;
import jodd.typeconverter.TypeConverterManager;
import lombok.*;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Set;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class FilterManage{


    private Set variables;

    private List<VarFilter> filterList;

    private FilterManage(VariableBuilder varBuilder) {
        this.filterList = varBuilder.filterList;
    }

    public static VariableBuilder vars(Set vars) {
        return new VariableBuilder().addVariable(vars);
    }


    public static class VariableBuilder {

        @Setter(value = AccessLevel.PRIVATE)
        private Set variables;
        private List<VarFilter> filterList;

        public VariableBuilder addFilter(VarFilter filter) {
            filterList.add(filter);
            return this;
        }

        private VariableBuilder addVariable(Set variables) {
            this.setVariables(variables);
            this.filterList = Lists.newArrayList();
            return this;
        }

        public <C extends Set<T>, T> C invokerFilter(Class<T> returnType) {
            FilterManage filterManage = new FilterManage(this);
            filterManage.setVariables(variables);
            filterManage.setFilterList(filterList);
            filterManage.getFilterList().forEach(filter -> {
                Set variables = filterManage.getVariables();
                if (CollectionUtils.isNotEmpty(variables)) {
                    filterManage.setVariables(filter.actionVar(variables));
                }
            });
            return TypeConverterManager.get().convertToCollection(filterManage.getVariables(), Set.class, returnType);
        }
    }
}
